from django.http import HttpResponse
from django.core.files.storage import FileSystemStorage

from ...utils.users import get_login_user_id, rand_num_file


from ...models.chat_file_upload import ChatFiles

import json, os, datetime


def upload_file(request):
    '''
    公告文件上传
    公告图片上传

    POST
    res = {
        "name": "(1).jpg",
        "obj_key": "./static/upload/2024/7/1720665761541415.jpg",
        "size": 29818,
        "url": "/static/upload/2024/7/1720665761541415.jpg",
        "ext": ".jpg"
    }
    '''
    if request.method == 'POST':
        if request.FILES:
            # 获取用户id
            userid = get_login_user_id(request, isadmin=True)
            # 获取上传的文件 以及一些需要的信息
            uploaded_file = request.FILES['file']
            uploaded_file_name = uploaded_file.name
            uploaded_file_size = uploaded_file.size
            uploaded_file_ext = "." + uploaded_file_name.split('.')[-1]

            time_path = "systems/" + datetime.datetime.now().strftime("%Y/%m/%d")

            # 创建保存文件的实例
            fs = FileSystemStorage()

            # 创建保存文件的基础路径
            os.makedirs(os.path.join(fs.location, time_path), exist_ok=True)

            # 随机生成16位数字文件名称
            rand_file_name = rand_num_file(uploaded_file_ext)

            # 获取保存文件的路径
            file_path = os.path.join(time_path, rand_file_name)

            # 保存文件
            try:
                filename = fs.save(file_path, uploaded_file)
            except:
                res_mes = {
                    "code": 1,
                    "message": "文件保存失败！"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)

            visit_url = fs.url(filename)

            # 创建数据库信息
            try:
                ChatFiles.objects.create(
                    user_id = userid,
                    name = uploaded_file_name,
                    obj_key = visit_url,
                    url = visit_url,
                    ext = uploaded_file_ext,
                    size = uploaded_file_size,
                    img = file_path,
                    avatar = False,
                )
            except:
                res_mes = {
                    "code": 1,
                    "message": "文件信息保存失败！"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)
            
            # 返回数据
            res_mes = {
                "code": 0,
                "data": {
                    "ext": uploaded_file_ext,
                    "name": uploaded_file_name,
                    "obj_key": visit_url,
                    "size": uploaded_file_size,
                    "url": visit_url
                }
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        
        else:
            res_mes = {
                "code": 1,
                "message": "请上传文件！"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)

